package com.apinji.unionpay;

import com.apinji.common.domain.wrapper.Reply;
import com.apinji.common.plugin.DateUtils;
import com.apinji.common.plugin.Mutual;
import com.apinji.common.plugin.StrUtils;
import com.apinji.unionpay.dto.*;
import com.apinji.unionpay.service.BankCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 轩辕夏夏 on 2017/7/1.
 *
 * 用戶銀行卡管理
 * 1.查詢常用卡
 * 2.查詢銀行卡是否已經綁定token
 */
@RestController
@EnableAutoConfiguration
@EnableAsync
@RequestMapping("/v1.0/card")
public class BankCardController {

    @Autowired
    private BankCardService bankCardService;


    @RequestMapping("/hello")
    @ResponseBody
    public String home() {
        String t = DateUtils.getCurrentDateTime();
        String t1 = new Timestamp(new Date().getTime()).toString();
        return "Hello World, now:" + t + "             " + t1;
    }

    /**
     * 查询用户常用的银行卡
     * @param userUUID
     * @return
     */
    @RequestMapping(value = "/getInUsedCards")
    public Reply getInUsedCards(@RequestParam String userUUID) {
        return bankCardService.getInUsedCards(userUUID);
    }

    /**
     * 查询该卡是否开通过(查询自己是否已经开通过该卡)
     *
     * @param queryIsOpenDto
     * @return  如果已经开通，返回该卡的token绑定信息
     */
    @RequestMapping(value = "/isOpen")
    public Reply isOpen(@RequestBody QueryIsOpenDto queryIsOpenDto) {
        if(StrUtils.isEmpty(queryIsOpenDto.getUserUUID())) {
            return Mutual.invalidParamAppend("userUUID");
        }
        if(StrUtils.isEmpty(queryIsOpenDto.getCardNo())) {
            return Mutual.invalidParamAppend("cardNo");
        }
        return bankCardService.isOpen(queryIsOpenDto);
    }

    /**
     * 删除用户常用卡
     * @param delUsedCardDto
     * @return
     */
    @RequestMapping(value = "/delUserCard")
    public Reply delUserCard(@RequestBody DelUsedCardDto delUsedCardDto) {
        if(StrUtils.isEmpty(delUsedCardDto.getId())) {
            return Mutual.invalidParamAppend("id");
        }
        if(StrUtils.isEmpty(delUsedCardDto.getUserUUID())) {
            return Mutual.invalidParamAppend("userUUID");
        }
        return bankCardService.delUserCard(delUsedCardDto);
    }


    /**
     * 银联支付后台开通时发送短信验证码到用户手机
     *
     * @param openCardSMSBackTokenDto
     * @return
     */
    @Deprecated
    @RequestMapping(value = "/openCardSMSBackToken")
    public Reply openCardSMSBackToken(@RequestBody OpenCardSMSBackTokenDto openCardSMSBackTokenDto){
        if(StrUtils.isEmpty(openCardSMSBackTokenDto.getCardNo())) {
            return Mutual.invalidParamAppend("cardNo");
        }
        if(StrUtils.isEmpty(openCardSMSBackTokenDto.getPhoneNo())) {
            return Mutual.invalidParamAppend("phoneNo");
        }
        if(StrUtils.isEmpty(openCardSMSBackTokenDto.getOrderId())) {
            return Mutual.invalidParamAppend("orderId");
        }
        if(StrUtils.isEmpty(openCardSMSBackTokenDto.getUserUUID())) {
            return Mutual.invalidParamAppend("userUUID");
        }
        return bankCardService.openCardSMSBackToken(openCardSMSBackTokenDto);
    }

    /**
     * 银联支付 后台开通
     * token方式的后台开通，无需前台跳转到银联界面
     * @param openCardBackTokenDto
     * @return
     */
    @Deprecated
    @RequestMapping(value = "/openCardBackToken", method = RequestMethod.POST)
    public Reply openCardBackToken(@RequestBody OpenCardBackTokenDto openCardBackTokenDto) throws IOException {
        //TODO 数据校验
        return bankCardService.openCardBackToken(openCardBackTokenDto);
    }


    /**
     * 银联支付 开通
     * 跳转到银联界面进行开通
     *
     * @param request
     * @param response
     * @param openCardFrontTokenDto
     * @throws IOException
     */
    @RequestMapping(value = "/openCardFrontTokenBody")
    public Object openCardFrontToken(HttpServletRequest request, HttpServletResponse response, @RequestBody OpenCardFrontTokenDto openCardFrontTokenDto) throws IOException {
        response.setContentType("text/html; charset="+ "UTF-8");
        if(StrUtils.isEmpty(openCardFrontTokenDto.getUserUUID())){
            response.getWriter().write("参数错误：[userUUID]");
            return null;
        }
        if(StrUtils.isEmpty(openCardFrontTokenDto.getCardNo())) {
            response.getWriter().write("参数错误：[cardNo]");
            return null;
        }
        if(StrUtils.isEmpty(openCardFrontTokenDto.getOrderId())) {
            response.getWriter().write("参数错误：[orderId]");
            return null;
        }
        String regEx = "^([1-9]{1})(\\d{15}|\\d{17}|\\d{18})$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(openCardFrontTokenDto.getCardNo());
        // 字符串是否与正则表达式相匹配
        boolean rs = matcher.matches();
        if(!rs) {
            response.getWriter().write("银行卡号错误");
            return null;
        }
        //
        bankCardService.openCardFrontToken(request, response, openCardFrontTokenDto);
        return null;
    }

    /**
     * 银联支付 开通
     * 跳转到银联界面进行开通
     *
     * @param request
     * @param response
     * @param userUUID
     * @param cardNo
     * @param orderId
     * @param frontUrl
     * @throws IOException
     */
    @RequestMapping(value = "/openCardFrontToken")
    public Object openCardFrontToken(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) String userUUID,
                                     @RequestParam(required = false) String cardNo, @RequestParam(required = false) String orderId,
                                     @RequestParam(required = false) String frontUrl) throws IOException {
        response.setContentType("text/html; charset="+ "UTF-8");
        if(StrUtils.isEmpty(userUUID)){
            response.getWriter().write("参数错误：[userUUID]");
            return null;
        }
        if(StrUtils.isEmpty(cardNo)) {
            response.getWriter().write("参数错误：[cardNo]");
            return null;
        }
        if(StrUtils.isEmpty(orderId)) {
            response.getWriter().write("参数错误：[orderId]");
            return null;
        }
        String regEx = "^([1-9]{1})(\\d{15}|\\d{17}|\\d{18})$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(cardNo);
        // 字符串是否与正则表达式相匹配
        boolean rs = matcher.matches();
        if(!rs) {
            response.getWriter().write("银行卡号错误");
            return null;
        }
        //
        bankCardService.openCardFrontToken(request, response, userUUID, cardNo, orderId, frontUrl);
        return null;
    }


    /**
     * 跳转到银联界面开通回调(后台回调)
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/openCardFrontBackRcvResponse")
    public void callBackOpenCardFrontBackRcvResponse(HttpServletRequest request, HttpServletResponse response) throws Exception {
        bankCardService.openCardFrontBackRcvResponse(request, response);
    }


    /**
     * 跳转到银联界面开通回调(前台回调)-------------只用于测试
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/openCardFrontFrontRcvResponse")
    @ResponseBody
    public String callBackOpenCardFrontFrontRcvResponse(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return bankCardService.openCardFrontFrontRcvResponse(request, response);
    }

}
